{% extends "base.html" %}

{% block title %}专有云资源{% endblock %}

{% block head %}
  {{ super() }}
  <!-- DataTables -->
  <link rel="stylesheet" href="/static/css/dataTables.bootstrap.min.css">
  <!-- DataTables button -->

  <link rel="stylesheet" href="/static/css/buttons.bootstrap.min.css">
  <!-- DataTables searchPanes -->
  <link rel="stylesheet" href="/static/css/searchPanes.bootstrap.min.css">
  <link rel="stylesheet" href="/static/css/select.bootstrap.min.css">
  <link rel="stylesheet" href="/static/css/fixedColumns.bootstrap.min.css">




{% endblock %}

{% block content %}
  <!-- 页面头 -->
  <section class="content-header">
    <!--头部标题-->
    <h1>
      云资源
      <!--    <small>advanced tables</small>-->
    </h1>
    <!--面包屑-->
    <ol class="breadcrumb">
      <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
      <li>资产管理</li>
      <li class="active">云资源</li>
    </ol>
  </section>

  <!-- 页面内容 -->
  <section class="content">
    <div class="row">
      <div class="col-xs-12">
        <!--表格1-->
        <div class="box">
          <div class="box-header">
            <!--          <h3 class="box-title">公共平台</h3>-->
          </div>
          <div class="box-body table-responsive">
            <table id="example" class="table-hover nowrap table-bordered  table-condensed table-striped"
                   style="font-size: 90%;width:100%">
              <thead>
              <tr>
                <th style="text-align: center">组织</th>
                <th style="text-align: center">项目</th>
                <th style="text-align: center">类型</th>
                <th style="text-align: center">实例ID</th>
                <th style="text-align: center">内网IP</th>
                <th style="text-align: center">公网IP</th>
                <th style="text-align: center">CPU(C)</th>
                <th style="text-align: center">内存(G)</th>
                <th style="text-align: center">系统盘(G)</th>
                <th style="text-align: center">数据盘(G)</th>
                <th style="text-align: center">版本</th>
                <th style="text-align: center">资源功能</th>
                <th style="text-align: center">备注</th>
                <th style="text-align: center">CPU使用率</th>
                <th style="text-align: center">内存使用率</th>
                <th style="text-align: center">磁盘使用率</th>
                <th style="text-align: center">OSS用量(G)</th>
                <th style="text-align: center">过期时间</th>
              </tr>
              </thead>

              <tbody>
              <!-- 表格内容，由Datatables根据api返回自动填写 -->
              </tbody>
            </table>
          </div>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->

      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </section>
  <!-- /.页面内容 -->


  <!-- Modal excel导入弹框-->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">导入Excel数据</h4>
        </div>
        <div class="modal-body">
          <!--隐藏字段-->
          <input class="hidden" type="text" id="filename" value="">
          <p>1. 使用导出功能获得Excel模板，并编辑</p>
          <p>2. 上传Excel文件</p>
          <input type="file" id="uploadFile">&nbsp;
          <p>3. 选择Excel sheet：</p>
          <select class="form-control" disabled="disabled" id="selectSheet">
            <!--          <option>&#45;&#45;请选择表单&#45;&#45;</option>-->
          </select>
          &nbsp;
          <div class="callout">
            <p><strong>导入规则说明：</strong></p>
            <ul class="list-unstyled">
              <li>a. <span class="text-red">实例ID</span>必须唯一</li>
              <li>b. 若实例ID中不存在，则新增</li>
              <li>c. 若实例ID已存在，则更新</li>
            </ul>

          </div>

        </div>

        <div class="modal-footer">
          <!--        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>-->

          <button id="importBtn" type="button" class="btn btn-success" disabled="disabled">导入数据</button>
          <div id="loading" style="display: none"><p><i class='fa fa-spin fa-spinner'></i> 导入中...</p></div>

        </div>
      </div>
    </div>
  </div>

{% endblock %}


{% block script %}
  <!-- DataTables -->
  <script src="/static/js/jquery.dataTables.min.js"></script>
  <script src="/static/js/dataTables.bootstrap.min.js"></script>
  <!-- DataTables buttons-->
  <script src="/static/js/dataTables.buttons.min.js"></script>
  <script src="/static/js/buttons.bootstrap.min.js"></script>

  <script src="/static/js/jszip.min.js"></script>
  <script src="/static/js/pdfmake.min.js"></script>
  <script src="/static/js/vfs_fonts.js"></script>

  <script src="/static/js/buttons.html5.min.js"></script>
  <script src="/static/js/buttons.print.min.js"></script>
  <script src="/static/js/buttons.colVis.min.js"></script>



  {#  <script src="/static/js/buttons.colVis.min.js"></script>#}

  <!-- DataTables searchPanes-->
  <script src="/static/js/dataTables.searchPanes.min.js"></script>
  <script src="/static/js/searchPanes.bootstrap.min.js"></script>
  <script src="/static/js/dataTables.select.min.js"></script>

  <!-- DataTables others-->
  <script src="/static/js/dataTables.fixedColumns.min.js"></script>



  <!-- Page specific script -->
  <script>
      $(document).ready(function () {
          var table = $('#example').DataTable({
              //ajax: '/api/v1/cloud/resource',
              ajax: '/api/v1/cmdb/cloud_resource',
              columns: [
                  {data: 'org'},
                  {data: 'project'},
                  {data: 'res_type'},
                  {data: 'instance_id'},
                  {data: 'ip_private'},
                  {data: 'ip_public'},
                  {data: 'cpu'},
                  {data: 'mem'},
                  {data: 'sys_disk'},
                  {data: 'data_disk'},
                  {data: 'system_version'},
                  {data: 'res_function'},
                  {data: 'comment'},
                  {data: 'cpu_use_percent'},
                  {data: 'mem_use_percent'},
                  {data: 'disk_use_percent'},
                  {data: 'oss_use'},
                  {data: 'expire_time'},
              ],
              order: [[0, 'asc'], [1, 'asc'], [2, 'asc'], [3, 'asc']],
              fixedColumns: {
                  left: 0,
                  right: 0,
              },
              //paging: false,

              //scrollCollapse: false,
              scrollX: true,
              //scrollY: 300,
              select: true,
              processing: true,
              language: {
                  "url": "/static/language.json"
              },
              lengthChange: false,
              searchPanes: {
                  initCollapsed: true,
                  columns: [0, 1, 2]
              },
              responsive: false,
              autoWidth: false,
              stateSave: false,
              lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "全部"]],
              buttons: [
                  'pageLength',
                  {
                      extend: 'colvis',
                      titleAttr: '显示/隐藏列'
                  },
                  {
                      extend: 'excelHtml5',
                      sheetName: '云资源统计',
                      title: null,
                      filename: '云资源统计',
                      titleAttr: '导出Excel'
                  },
                  'upload',
                  'remove'
              ],
              columnDefs: [],
              initComplete: function () {
                  table.buttons().container().appendTo('#example_wrapper .col-sm-6:eq(0)')
                  table.searchPanes.container().prependTo(table.table().container());
                  table.searchPanes.resizePanes();
                  table.columns.adjust().draw();
              }
          });

          // 自定义按钮：导入
          $.fn.dataTable.ext.buttons.upload = {
              text: '导入',
              action: function (e, dt, node, config) {
                  $('#myModal').modal()
              }
          };

          // 自定义按钮：移除
          $.fn.dataTable.ext.buttons.remove = {
              extend: 'selected',
              text: '移除',
              action: function (e, dt, button, config) {
                  console.log(dt.rows({selected: true}).data())
                  rows_data = dt.rows({selected: true}).data()
                  var ins_ids = [];
                  for (let i = 0; i < rows_data.length; i++) {
                      ins_ids.push(rows_data[i].instance_id)
                      console.log(ins_ids)
                  }
                  let msg = "确定将下列实例移至回收站？<br>"
                  for (let i = 0; i < ins_ids.length; i++) {
                      msg += "<br>" + ins_ids[i]
                  }
                  bootbox.confirm({
                      message: msg,
                      buttons: {
                          confirm: {
                              label: '移 除',
                              className: 'btn-danger '
                          },
                          cancel: {
                              label: '取 消',
                              className: 'btn-default'
                          }
                      },
                      callback: function (result) {
                          if (result === true) {
                              remove_instances(ins_ids)
                          }
                      }
                  })


              }
          };

          // 传入实例id数组，将他们移动到废纸篓中
          function remove_instances(ins_ids) {
              var post_data = {
                  'type': 'cloud_resource',
                  'action': 'delete',
                  'ins_ids': ins_ids
              }
              $.ajax({
                  url: "/api/v1/cmdb/delete",
                  type: "POST",
                  data: JSON.stringify(post_data),
                  contentType: "application/json",
                  dataType: "json",
                  success: function (data) {
                      console.log(data);
                      let msg = "下列实例已移除至回收站："
                      for (let i = 0; i < ins_ids.length; i++) {
                          msg += "\n" + ins_ids[i]
                      }
                      table.ajax.reload();
                  }
              });
          }


          // 根据URL的search参数，自动搜索
          let searchString = getQueryString('search')
          if (searchString !== '') {
              console.log(searchString)
              table.search(searchString);
              table.draw();
          }

          // 解决sidebar toogle之后，datatables标题行错位问题
          //$('.sidebar-toggle').click(function () {
          //    $('.dataTables_scrollHeadInner').css('width', '100%');
          //    $('#example').css('width', '100%');
          //    setTimeout(function () {
          //        table.columns.adjust().draw();
          //    }, 400);
          //});

          //自动上传excel
          $('#uploadFile').change(function () {
              if ($(this).val() != '') {
                  // alert('uploading')
                  upload(this)
              }


          })
      });


      // 上传Excel文件
      function upload(ele) {
          var formData = new FormData();
          var name = $(ele).val();
          var file = $(ele)[0].files[0];
          formData.append('file', file);
          formData.append('name', name);
          $.ajax({
              url: "/api/v1/cmdb/upload",
              type: "POST",
              data: formData,
              contentType: false,
              cache: false,
              processData: false,
              success: function (data) {
                  console.log(data);
                  if (data.code == 500) {
                      alert("后台错误：" + data.error)
                  }

                  // alert(data)
                  // $('#selectSheet').find('option').remove()
                  // 上传成功后，显示所有sheet选择下拉框和上传按钮
                  for (let i in data.sheets_name) {
                      $('#selectSheet').append('<option value="' + data.sheets_name[i] + '">' + data.sheets_name[i] + '</option>')
                  }
                  $('#selectSheet').removeAttr('disabled');
                  $('#importBtn').removeAttr('disabled');
                  $('#filename').val(data.filename)
              }
          });
      }

      $('#importBtn').click(function () {
          $('#importBtn').attr('disabled', 'disabled')
          $('#loading').show()
          $.ajax({
              url: "/api/v1/cmdb/cloud_resource_update",
              headers: {Accept: "application/json; charset=utf-8"},
              type: "POST",
              data: {
                  type: 'cloud_resource',
                  filename: $('#filename').val(),
                  sheet_name: $('#selectSheet').val(),
              },
              success: function (data) {
                  console.log(data)
                  let t = "导入结果：新增" + data.insert_count + "行，更新" + data.change_count + "行，忽略" + data.ignore_count + "行"
                  alert(t)
                  $('#loading').text(t)
                  console.log('adgddd')
                  // $('#myModal').modal('hide')
              }
          })
      })

  </script>
{% endblock %}